package lovedna.net {
	import flash.display.Loader;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;

	/**
	 * ...
	 * @author liwei
	 */
	public class BaseLoader extends Loader implements ILoader {
		private var _urlRequest : URLRequest;
		private var _context : LoaderContext;

		public function BaseLoader() {
		}

		override public function load(request : URLRequest, context : LoaderContext = null) : void {
			if (request == null) {
				dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR, false, false, "加载的文件不存在"));
				return;
			}
			var clone : URLRequest = new URLRequest(request.url);
			clone.contentType = request.contentType;
			var ba : ByteArray = new ByteArray();
			ba.writeObject(request.data);
			ba.position = 0;
			clone.data = ba.readObject();
			clone.digest = request.digest;
			clone.method = request.method;
			clone.requestHeaders = request.requestHeaders;
			if (clone.requestHeaders != null) {
				clone.requestHeaders = request.requestHeaders.concat();
			}
			_urlRequest = clone;
			_context = context;
			if (request.data is ByteArray) {
				super.loadBytes(clone.data as ByteArray, context);
			} else {
				super.load(clone, context);
			}
		}

		public function start(request : URLRequest, context : LoaderContext = null) : void {
			load(request, context);
		}

		public function stopload() : void {
			unload();
			try {
				unloadAndStop(true);
			} catch(e : Error) {
			}
		}

		public function resume() : void {
			if (_urlRequest) {
				load(_urlRequest, _context);
			}
		}

		public function get urlRequest() : URLRequest {
			return _urlRequest;
		}

		public function get bytes() : ByteArray {
			if (contentLoaderInfo) {
				return contentLoaderInfo.bytes;
			}
			return null;
		}

		public function get dispatcher() : EventDispatcher {
			return this.contentLoaderInfo;
		}

		public function get data() : * {
			return contentLoaderInfo.content;
		}
	}
}